package com.huike.game.Activity;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.huike.game.R;
import com.huike.game.base.Game69;

import java.util.ArrayList;
import java.util.Calendar;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

public class GameActivity69Shoop extends AppCompatActivity implements View.OnClickListener {

    private ImageView iv_left_image;
    private TextView tv_left_text;
    private TextView tv_content_title;
    private ImageView iv_rigth_image;
    private TextView tv_right_text;
    private TextView tv_game69s_textTime;
    private TextView tv_game69s_dataTime;
    private ListView lv_game69s;
    private TextView tv_Game69_zongjia;
    private Button but_game69s_pay;
    private Button but_game69s_close;
    private Button but_game69s_dater;
    private ArrayList<Game69.DataBean> dataBeans;
    private ListViewAdapter adapter;
    private RequestQueue queue;
    private int money = 0;//总金额
    private Boolean isClick = false;//删除按钮显示开关
    //但前日期
    private int dyear;
    private int moth;
    private int days;
    //选择日期
    private int tyear;
    private int tmonth ;
    private int tdayOfMonth ;//默认等于当前日期
    private ViewHolder holder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game_activity69_shoop);
        queue = Volley.newRequestQueue(this);
        dataBeans = new ArrayList<>();
        //初始化当前日期
        final Calendar instance = Calendar.getInstance();
        dyear = instance.get(Calendar.YEAR);
        moth = instance.get(Calendar.MONTH);
        days = instance.get(Calendar.DAY_OF_MONTH);
        //初始化选择日期默认值
        tyear = dyear;
        tmonth = moth;
        tdayOfMonth = days;
        initView();
        initdata();
        adapter = new ListViewAdapter();
        lv_game69s.setAdapter(adapter);
        int monthday = moth + 1;
        String val = monthday +"/"+days;
        tv_game69s_textTime.setText("今天"+val +"\n预定");

        //更多时间点击
        tv_game69s_dataTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DatePickerDialog dialog = new DatePickerDialog(GameActivity69Shoop.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        int monthday = month + 1;
                        String val = monthday +"/"+dayOfMonth;

                        tyear = year;
                        tmonth = month;
                        tdayOfMonth = dayOfMonth;

                        if(dyear == year && moth == month && days == dayOfMonth){
                            tv_game69s_textTime.setText("今天"+val +"\n预定");
                            tv_game69s_textTime.setTextColor(Color.parseColor("#ff000000"));
                        }else{
                            tv_game69s_textTime.setText(val +"\n预定");
                            tv_game69s_textTime.setTextColor(Color.parseColor("#E499A2A2"));
                        }
                    }
                },instance.get(Calendar.YEAR),instance.get(Calendar.MONTH ),instance.get(Calendar.DAY_OF_MONTH));

                dialog.show();

            }
        });

//        使用日期点击
        but_game69s_dater.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(dyear ==tyear && moth == tmonth && days == tdayOfMonth ){
                    tv_game69s_textTime.setTextColor(Color.parseColor("#ff000000"));
                }else{
                    int mm = tmonth + 1;
                    tv_game69s_textTime.setTextColor(Color.parseColor("#E499A2A2"));
                }

            }
        });


        lv_game69s.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });



    }

    private void initdata() {

        SharedPreferences list = getSharedPreferences("game69list", MODE_PRIVATE);
        String data = list.getString("data", null);
        Log.e("---",data);

        String[] split = data.split("-");
        for (int i = 0; i < split.length; i++) {
            Game69.DataBean bean = new Gson().fromJson(split[i], Game69.DataBean.class);
            dataBeans.add(bean);

            //计算总计额
            int price = dataBeans.get(i).getPrice();
            money += price;
        }

        tv_Game69_zongjia.setText("总金额:"+money);


    }

    private void initView() {
        iv_left_image = (ImageView) findViewById(R.id.iv_left_image);
        tv_left_text = (TextView) findViewById(R.id.tv_left_text);
        tv_content_title = (TextView) findViewById(R.id.tv_content_title);
        iv_rigth_image = (ImageView) findViewById(R.id.iv_rigth_image);
        tv_right_text = (TextView) findViewById(R.id.tv_right_text);

        tv_game69s_textTime = (TextView) findViewById(R.id.tv_game69s_textTime);
        tv_game69s_dataTime = (TextView) findViewById(R.id.tv_game69s_dataTime);

        lv_game69s = (ListView) findViewById(R.id.lv_game69s);
        tv_Game69_zongjia = (TextView) findViewById(R.id.tv_Game69_zongjia);
        but_game69s_pay = (Button) findViewById(R.id.but_game69s_pay);
        but_game69s_dater = (Button) findViewById(R.id.but_game69s_dater);
        but_game69s_pay.setOnClickListener(this);
        but_game69s_close = (Button) findViewById(R.id.but_game69s_close);
        but_game69s_close.setOnClickListener(this);


        iv_rigth_image.setVisibility(View.GONE);
        iv_left_image.setImageResource(R.drawable.tiao);
        tv_content_title.setText("购物车");
        tv_left_text.setVisibility(View.GONE);
        tv_right_text.setText("管理");


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.but_game69s_pay://支付

                //得到总价钱
                String zMoneyNum = tv_Game69_zongjia.getText().toString();
                String zongjia = zMoneyNum.substring(zMoneyNum.lastIndexOf(":") + 1);
                //带到下一个页面
                Intent intent = new Intent(GameActivity69Shoop.this,GameActivity69QC.class);
                intent.putExtra("game69_val",zongjia);
                startActivity(intent);

                break;
            case R.id.but_game69s_close://清空购物车

                //先来个提示把
                AlertDialog dialog = new AlertDialog.Builder(GameActivity69Shoop.this)
                        .setTitle("我是标题啊")
                        .setMessage("真的要清空购物车吗!")
                        .setCancelable(false) /*点击空白处，不会退出对话框，要点击返回键才会退出*/
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //清空数据
                                dataBeans.clear();
                                //更新总价
                                tv_Game69_zongjia.setText("总价钱:"+0);
                                //通知适配器跟新
                                adapter.notifyDataSetChanged();

                                //更新缓存
                                SharedPreferences list = getSharedPreferences("game69list", MODE_PRIVATE);
                                list.edit().putString("data","").commit();
                            }
                        })
                        .setNegativeButton("取消", null).create();

                dialog.show();



                break;
        }
    }

    class ListViewAdapter extends BaseAdapter {

        private Game69.DataBean bean;

        @Override
        public int getCount() {
            return dataBeans.size();
        }

        @Override
        public Object getItem(int position) {
            return dataBeans.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            holder = null;
            if (convertView == null) {
                convertView = View.inflate(GameActivity69Shoop.this, R.layout.lv_game69, null);
                    holder = new ViewHolder(convertView);
                    convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            bean = dataBeans.get(position);

            holder.tv_game69ls_title.setText(bean.getName());

            ImageRequest request = new ImageRequest(bean.getImage(), new Response.Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap bitmap) {
                    holder.iv_game69ls_image.setImageBitmap(bitmap);
                }
            },0,0, ImageView.ScaleType.CENTER, Bitmap.Config.ARGB_8888,null);

            queue.add(request);

            holder.tv_Game69ls_desc.setText(bean.getContent());
            holder.tv_game69ls_price.setText(bean.getPrice()+"元");

            if(isClick){
                holder.tv_game69ls_del.setVisibility(View.VISIBLE);
            }else{
                holder.tv_game69ls_del.setVisibility(View.INVISIBLE);
            }


//            加号点击
            final View finalConvertView = convertView;
            holder.tv_game69ls_jia.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.e("---",position +"");

                    String num = holder.tv_game69ls_num.getText().toString();
                    int numPric = Integer.parseInt(num);

                    numPric++;

                    if(numPric == 999){
                        Toast.makeText(GameActivity69Shoop.this, "最大了", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    //得到当前的价钱
                    int price = bean.getPrice();
                    holder.tv_game69ls_num.setText(numPric+"");//设置数量
                    //得到总价格
                    String zMoneyNum = tv_Game69_zongjia.getText().toString();
                    //截取字符串得到总价
                    String zongjia = zMoneyNum.substring(zMoneyNum.lastIndexOf(":") + 1);
                    int zMoney = Integer.parseInt(zongjia) +price;//计算价钱

                    tv_Game69_zongjia.setText("总金额:" + zMoney);
                    adapter.notifyDataSetChanged();



                }
            });

            //减号点击
            holder.tv_game69ls_jian.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String num = holder.tv_game69ls_num.getText().toString();
                    int numPric = Integer.parseInt(num);

                    numPric--;

                    if(numPric == 0){
                        Toast.makeText(GameActivity69Shoop.this, "最小了", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    //得到当前的价钱
                    int price = bean.getPrice();
                    holder.tv_game69ls_num.setText(numPric+"");//设置数量
                    //得到总价格
                    String zMoneyNum = tv_Game69_zongjia.getText().toString();
                    //截取字符串得到总价
                    String zongjia = zMoneyNum.substring(zMoneyNum.lastIndexOf(":") + 1);
                    int zMoney = Integer.parseInt(zongjia)  - price;//计算价钱

                    Log.e("---",zMoney +"");
                    tv_Game69_zongjia.setText("总金额:" + zMoney);
                    adapter.notifyDataSetChanged();

                }
            });

            //删除点击

            holder.tv_game69ls_del.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //得到点击删除这行的价钱
                    int price = bean.getPrice();
                    //得到数量
                    String num = holder.tv_game69ls_num.getText().toString();
                    int sum =  price * Integer.parseInt(num);

                    //得到总价格
                    String zMoneyNum = tv_Game69_zongjia.getText().toString();
                    //截取字符串得到总价
                    String zongjia = zMoneyNum.substring(zMoneyNum.lastIndexOf(":") + 1);
                    int zMoney = Integer.parseInt(zongjia)  - sum;//计算价钱
                    //更新总价
                    tv_Game69_zongjia.setText("总金额:" + zMoney);

                    //移除这行数据
                    dataBeans.remove(position);

                    adapter.notifyDataSetChanged();//通知适配器更新数据

                    //更新缓存
                    if(!dataBeans.isEmpty()){//不为空
                        ArrayList<String> arrayList = new ArrayList<>();
                        StringBuffer  buffer  = new StringBuffer();
                        for (int i = 0; i < dataBeans.size(); i++) {
                            //将对象变为字符串
                            String json = new Gson().toJson(dataBeans.get(i));
                            //添加字符数组
                            arrayList.add(json);
                            //追加
                            buffer.append(arrayList.get(i)).append("-");
                        }

                        SharedPreferences list = getSharedPreferences("game69list", MODE_PRIVATE);
                        list.edit().putString("data",buffer.toString()).commit();
                    }else{//为空的话直接添加空字符串
                        SharedPreferences list = getSharedPreferences("game69list", MODE_PRIVATE);
                        list.edit().putString("data","").commit();

                    }


                }
            });


            //管理开关
            tv_right_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if(isClick){
                        isClick = false;
                        adapter.notifyDataSetChanged();
                    }else{
                        isClick = true;
                        adapter.notifyDataSetChanged();
                    }

                }
            });


            return convertView;
        }


    }
    class ViewHolder {
        public View rootView;
        public TextView tv_game69ls_del;
        public ImageView iv_game69ls_image;
        public TextView tv_game69ls_title;
        public TextView tv_Game69ls_desc;
        public TextView tv_game69ls_jian;
        public TextView tv_game69ls_num;
        public TextView tv_game69ls_jia;
        public TextView tv_game69ls_price;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.tv_game69ls_del = (TextView) rootView.findViewById(R.id.tv_game69ls_del);
            this.iv_game69ls_image = (ImageView) rootView.findViewById(R.id.iv_game69ls_image);
            this.tv_game69ls_title = (TextView) rootView.findViewById(R.id.tv_game69ls_title);
            this.tv_Game69ls_desc = (TextView) rootView.findViewById(R.id.tv_Game69ls_desc);
            this.tv_game69ls_jian = (TextView) rootView.findViewById(R.id.tv_game69ls_jian);
            this.tv_game69ls_num = (TextView) rootView.findViewById(R.id.tv_game69ls_num);
            this.tv_game69ls_jia = (TextView) rootView.findViewById(R.id.tv_game69ls_jia);
            this.tv_game69ls_price = (TextView) rootView.findViewById(R.id.tv_game69ls_price);
        }

    }
}
